<template>
  <el-dialog
    v-model="dialogVisible"
    title="分享文件"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div v-if="resource" class="share-container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="资源名称">
          <el-input :value="resource.name" disabled />
        </el-form-item>
        
        <el-form-item label="分享名称" prop="shareName">
          <el-input
            v-model="form.shareName"
            placeholder="请输入分享名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="访问级别" prop="accessLevel">
          <el-radio-group v-model="form.accessLevel" @change="handleAccessLevelChange">
            <el-radio label="public">公开</el-radio>
            <el-radio label="password">密码保护</el-radio>
            <el-radio label="restricted">受限</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          v-if="form.accessLevel === 'password'"
          label="分享密码"
          prop="sharePassword"
        >
          <el-input
            v-model="form.sharePassword"
            placeholder="请输入分享密码"
            maxlength="32"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="有效期">
          <el-radio-group v-model="form.expireType" @change="handleExpireTypeChange">
            <el-radio label="permanent">永久有效</el-radio>
            <el-radio label="custom">自定义</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item
          v-if="form.expireType === 'custom'"
          label="过期时间"
          prop="expireTime"
        >
          <el-date-picker
            v-model="form.expireTime"
            type="datetime"
            placeholder="选择过期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        
        <el-form-item label="权限设置">
          <el-checkbox v-model="form.allowDownload">允许下载</el-checkbox>
          <el-checkbox v-model="form.allowPreview">允许预览</el-checkbox>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
          :loading="loading"
        >
          创建分享
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { shareApi } from '@/api/cd'

interface Props {
  visible: boolean
  resource: { type: string; id: number | string; name: string } | null
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'share-success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

const formRef = ref()
const loading = ref(false)

const form = reactive({
  shareName: '',
  accessLevel: 'public',
  sharePassword: '',
  expireType: 'permanent',
  expireTime: '',
  allowDownload: true,
  allowPreview: true
})

const rules = {
  shareName: [
    { required: true, message: '请输入分享名称', trigger: 'blur' },
    { min: 1, max: 100, message: '分享名称长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  accessLevel: [
    { required: true, message: '请选择访问级别', trigger: 'change' }
  ],
  sharePassword: [
    { 
      required: true, 
      message: '请输入分享密码', 
      trigger: 'blur',
      validator: (rule: any, value: string, callback: Function) => {
        if (form.accessLevel === 'password' && !value) {
          callback(new Error('请输入分享密码'))
        } else {
          callback()
        }
      }
    }
  ],
  expireTime: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (form.expireType === 'custom' && !value) {
          callback(new Error('请选择过期时间'))
        } else if (value && new Date(value) <= new Date()) {
          callback(new Error('过期时间必须大于当前时间'))
        } else {
          callback()
        }
      }
    }
  ]
}

const handleAccessLevelChange = () => {
  if (form.accessLevel !== 'password') {
    form.sharePassword = ''
  }
}

const handleExpireTypeChange = () => {
  if (form.expireType === 'permanent') {
    form.expireTime = ''
  }
}

const handleSubmit = async () => {
  if (!formRef.value || !props.resource) return
  
  try {
    await formRef.value.validate()
    
    loading.value = true
    
    const params = {
      shareType: props.resource.type,
      resourceId: props.resource.id,
      shareName: form.shareName,
      sharePassword: form.accessLevel === 'password' ? form.sharePassword : undefined,
      expireTime: form.expireType === 'custom' ? form.expireTime : undefined,
      accessLevel: form.accessLevel,
      allowDownload: form.allowDownload,
      allowPreview: form.allowPreview
    }
    
    const response = await shareApi.create(params)
    
    ElMessage.success('分享创建成功')
    emit('share-success')
    handleClose()
    
  } catch (error) {
    if (error !== false) {
      console.error('创建分享失败:', error)
      ElMessage.error('创建分享失败')
    }
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  form.shareName = ''
  form.accessLevel = 'public'
  form.sharePassword = ''
  form.expireType = 'permanent'
  form.expireTime = ''
  form.allowDownload = true
  form.allowPreview = true
  
  formRef.value?.clearValidate()
  dialogVisible.value = false
}
</script>

<style scoped lang="scss">
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
